package com.baiytfp.hf.HFDataExchange.common.base.realm;

import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.model.table.User_account;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;

import com.baiytfp.hf.baiytfp.framework.shiro.HFRealm;
import com.baiytfp.hf.baiytfp.hfutils.HFDBHelper;

public class UserAuthReaml extends HFRealm{
	public String getName() {
        return "hfRealm";
    }

    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken; //仅支持UsernamePasswordToken类型的Token
    }

    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    	String username = (String)token.getPrincipal();  //得到用户名
        String password = new String((char[])token.getCredentials()); //得到密码

        try {
        	User_account userVO = HFDBHelper.read(TableName.USER_ACCOUNT, " where user_code=? ", User_account.class, username);

//            LogUtil.debug(username + ":" + password + ":" + userVO.getUser_password());
            if(userVO != null){
                if(!password.equalsIgnoreCase(userVO.getUser_password())){    //密码不对
                    throw new IncorrectCredentialsException(); //如果密码错误
                }
            }else{
                throw new UnknownAccountException(); //如果用户名错误
            }
        }catch (UnknownAccountException ukae){
            throw ukae; //如果用户名错误
        }catch (IncorrectCredentialsException ice){
            throw ice; //如果密码错误
        }catch (Exception e){
            e.printStackTrace();    //其他错误
        }
        
        //如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
